package com.hualan.sfzy.service.counselor.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hualan.sfzy.constant.CommonConstant;
import com.hualan.sfzy.entity.counselor.Counselor;
import com.hualan.sfzy.entity.counselor.CounselorGrade;
import com.hualan.sfzy.entity.counselor.CounselorPriceClassify;
import com.hualan.sfzy.entity.counselor.Talent;
import com.hualan.sfzy.entity.system.Role;
import com.hualan.sfzy.entity.system.User;
import com.hualan.sfzy.mapper.counselor.*;
import com.hualan.sfzy.mapper.system.RoleMapper;
import com.hualan.sfzy.mapper.system.UserMapper;
import com.hualan.sfzy.mapper.system.UserRoleMapper;
import com.hualan.sfzy.service.counselor.CounselorService;
import com.hualan.sfzy.utils.MD5Util;
import com.hualan.sfzy.utils.SaltUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("CounselorService")
public class CounselorServiceImpl implements CounselorService {
    @Autowired
    private CounselorMapper counselorMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private TalentMapper talentMapper;
    @Autowired
    private CounselorGradeMapper counselorGradeMapper;
    @Autowired
    private CounselorPriceClassifyMapper counselorPriceClassifyMapper;

    // 咨询师对应的角色名称（根据实际业务调整）
    private static final String COUNSELOR_ROLE_NAME = "咨询师";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Counselor add(Counselor counselor) {  // 修改返回类型为Counselor，便于回传id
        // 1. 插入咨询师表（mybatis会自动回填自增id）
        counselorMapper.insert(counselor);
        // 此时counselor.getId()已获取到数据库自增的id

        // 2. 插入系统用户表
        User user = new User();
        user.setUsername(counselor.getMobile());
        user.setMobile(counselor.getMobile());
        user.setEmail(counselor.getEmail());
        user.setNickname(counselor.getCounselorName());
        String salt = SaltUtils.generateRandomSalt();
        user.setSalt(salt);
        String password = "123456" + salt;  // 初始密码+盐值
        user.setPassword(MD5Util.encode(password));
        userMapper.insert(user);  // 插入用户表，获取用户id

        // 3. 处理角色关联（核心修复部分）
        // 3.1 查询咨询师角色是否存在
        Role roleQuery = new Role();
        roleQuery.setRoleName(COUNSELOR_ROLE_NAME);  // 使用明确的角色名称查询
        List<Role> roles = roleMapper.select(roleQuery);

        Role counselorRole;
        if (roles.isEmpty()) {
            counselorRole = new Role();
            counselorRole.setRoleName(COUNSELOR_ROLE_NAME);
            roleMapper.insert(counselorRole);
            System.out.println("创建新角色：" + COUNSELOR_ROLE_NAME);
        } else {
            // 3.3 角色存在则使用已有角色
            counselorRole = roles.get(0);
            System.out.println("使用已有角色：" + COUNSELOR_ROLE_NAME);
        }

        // 3.4 建立用户-角色关联
        Map<String, Object> userRoleMap = new HashMap<>();
        userRoleMap.put("user_id", user.getId());  // 用户表id
        userRoleMap.put("role_id", counselorRole.getId());  // 角色表id
        userRoleMapper.insert(userRoleMap);

        // 返回包含id的咨询师对象给前端
        return counselor;
    }

    @Override
    public int remove(Integer id) {
        return counselorMapper.delete(id);
    }

    @Override
    public int removeBatch(Integer[] ids) {
        return counselorMapper.deleteBatch(ids);
    }

    @Override
    public int edit(Counselor counselor) {
        return counselorMapper.update(counselor);
    }

    @Override
    public Counselor findById(Integer id) {
        return counselorMapper.selectById(id);
    }

    @Override
    public Map<String, Object> findByPage(Integer pageNum, Integer pageSize, Counselor counselor) {
        PageHelper.startPage(pageNum, pageSize);
        List<Counselor> list = counselorMapper.select(counselor);
        PageInfo<Counselor> pageInfo = new PageInfo<>(list);
        Map<String, Object> map = new HashMap<>();
        map.put(CommonConstant.PAGE_LIST, list);
        map.put(CommonConstant.PAGE_TOTAL, pageInfo.getPages());
        map.put(CommonConstant.TOTAL, pageInfo.getTotal());
        return map;
    }

    @Override
    public List<Counselor> find() {
        return counselorMapper.select(null);
    }

    @Override
    public List<Counselor> findc() {
        return counselorMapper.selectc(null);
    }

    @Override
    public HashMap<String, Object> sift() {
        List<Talent> talents = talentMapper.select(null);
        List<CounselorGrade> grades = counselorGradeMapper.select(null);
        List<CounselorPriceClassify> priceClassifies = counselorPriceClassifyMapper.select(null);
        HashMap<String, Object> map = new HashMap<>();
        map.put("talents", talents);
        map.put("grades", grades);
        map.put("priceClassifies", priceClassifies);
        return map;
    }

    @Override
    public List<Counselor> findFilter(Counselor counselor) {
        return counselorMapper.selectFilter(counselor);
    }
}
